﻿using System;
using System.Linq;
using System.Reflection;

namespace QQ2564874169.RelationalSql.Trigger
{
    public interface ISchemaCreater : IDisposable
    {
        void CreateTable(Type tableModel);
        void CreateIndex(PropertyInfo[] columns);
    }

    public class MssqlSchemaCreater : ISchemaCreater
    {
        private ISql _sql;

        public MssqlSchemaCreater(ISql sql)
        {
            _sql = sql;
        }

        public void Dispose()
        {
            _sql?.Dispose();
            _sql = null;
        }

        public void CreateTable(Type tableModel)
        {
            var sql = $@"
            IF OBJECT_ID('{tableModel.Name}') IS NULL
            BEGIN
	            CREATE TABLE {tableModel.Name}(
		            [Id] NVARCHAR(50) NOT NULL PRIMARY KEY,
		            [Name] NVARCHAR(50),
                    [Type] INT,
                    [TableType] NVARCHAR(100),
                    [EntityType] NVARCHAR(100),
		            [Entity] NVARCHAR(MAX),
		            [CreateTime] BIGINT,
                    [Processed] BIT,
                    [ProcessTime] BIGINT,
                    [State] NVARCHAR(MAX)
	            )
            END";
            _sql.Execute(sql);
        }

        public void CreateIndex(PropertyInfo[] columns)
        {
            var tab = columns.First().DeclaringType.Name;
            var name = "IDX_" + string.Join("_", columns.Select(i => i.Name));
            var fields = string.Join(",", columns.Select(i => $"[{i.Name}]"));
            var sql = $@"
            IF (NOT EXISTS (SELECT 1 FROM sysindexes  WHERE id=OBJECT_ID('{tab}') AND name='{name}'))
                CREATE INDEX {name} ON [{tab}]({fields}) WITH(ONLINE=OFF)
            ";
            _sql.Execute(sql);
        }
    }
}
